#include "deepseek.h"
#include "ui_deepseek.h"
#include<QUrl>
#include<QNetworkRequest>
#include<QJsonArray>
#include<QJsonObject>
#include<QJsonDocument>
#include<QNetworkReply>
#include<QDebug>
#include<QJsonParseError>
DeepSeek::DeepSeek(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::DeepSeek)
{
    //sk-16d786eecd5949fc89f73f59cce864c1


    ui->setupUi(this);
    manager = new QNetworkAccessManager(this);
    connect(ui->exitBtn,&QPushButton::clicked,this,&DeepSeek::showMenu);
}

DeepSeek::~DeepSeek()
{
    delete ui;
}
//发送按钮，点击发送信息
void DeepSeek::on_seedBtn_clicked()
{


    QString text = ui->inputEdit->toPlainText();

    ui->inputEdit->clear();

    ui->outputEdit->insertPlainText("-->");
    ui->outputEdit->insertPlainText(text);
    ui->outputEdit->insertPlainText("\n\n");

    // 创建网络请求对象
    QNetworkRequest request;

    // 设置 API 端点 URL
    request.setUrl(QUrl("https://api.deepseek.com/chat/completions"));

    // 设置内容类型为 JSON
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

    // 设置接受 JSON 响应
    request.setRawHeader("Accept", "application/json");

    // 设置认证头（包含 API 密钥）
    request.setRawHeader("Authorization", "Bearer sk-16d786eecd5949fc89f73f59cce864c1");

    // 创建 JSON 数组来存储消息历史
    QJsonArray messages;

    // 创建系统消息的 JSON 对象
    QJsonObject systemMsg;
    systemMsg["role"] = "system";  // 键值对：角色
    systemMsg["content"] = "You are a helpful assistant";  // 键值对：内容

    // 创建用户消息的 JSON 对象
    QJsonObject userMsg;
    userMsg["role"] = "system";    // 注意：这里应该是 "user" 而不是 "system"
    userMsg["content"] = text;     // 用户输入的内容

    // 将两个消息对象添加到消息数组中
    messages.append(systemMsg);
    messages.append(userMsg);

    // 创建主请求体的 JSON 对象
    QJsonObject requestBody;
    requestBody["messages"] = messages;      // 包含消息数组
    requestBody["model"] = "deepseek-chat";  // 模型名称
    requestBody["max_tokens"] = 4096;        // 最大令牌数
    requestBody["stream"] = true;            // 使用流式响应
    requestBody["temperature"] = 1;          // 温度参数（控制随机性）

    QNetworkReply *reply = manager->post(request,QJsonDocument(requestBody).toJson());
    //发送数据


    //处理数据
    connect(reply,&QNetworkReply::readyRead,this,[=](){
        while(reply->canReadLine())
        {
            QString line = reply->readLine().trimmed();
            if(line.startsWith("data: "))//以ｄａｔａ：　开头的数据留下
            {
                line.remove(0,6);
                QJsonParseError error;
                QJsonDocument doc = QJsonDocument::fromJson(line.toUtf8(),&error);

                if(error.error==QJsonParseError::NoError){
                    QString content = doc.object()["choices"].toArray().first()
                            .toObject()["delta"].toObject()["content"].toString();

                    if(!content.isEmpty())
                    {
                        ui->outputEdit->moveCursor(QTextCursor::End);
                        ui->outputEdit->insertPlainText(content);
                    }
                }
            }
        }
    });

    //
    connect(reply,&QNetworkReply::finished,this,[=](){
        ui->outputEdit->moveCursor(QTextCursor::End);
        ui->outputEdit->insertPlainText("\n\n\n\n\n");


        reply->deleteLater();
    });



}
void DeepSeek::on_clearBtn_clicked()
{
    ui->outputEdit->clear();
}
